
package stcu;

import stcu.robjects.*;
import com.nvlled.route.*;

import java.util.*;

public class GroupAccess {

    private static final long TIMEOUT = 2000; // milliseconds

    private ObjectRouter router;
    private GroupDemux demux;

    public GroupAccess(ObjectRouter router, GroupDemux demux) {
        this.router = router;
        this.demux = demux;
    }

    public GroupAccess(ObjectRouter router) {
        this(router, new GroupDemux(router));
    }

    public Group create(Account account, String title) {
        RequestInfo info = new RequestInfo(
                GroupCreate.Status.class, 1,
                TIMEOUT, true);

        List<GroupCreate.Status> statuses = router.deliverSync(new GroupCreate(account, title), info, "default");
        if (statuses.isEmpty()) {
            throw new GroupOperationException("No response");
        }
        GroupCreate.Status s = statuses.get(0);
        if (s.failed()) {
            throw new GroupOperationException("Group creation denied: " + s.getCode());
        }

        AddressTable table = router.getTable();
        table.store(s.getGroupId(), router.getLocalAddress());
        table.store(account.getIDNumber(), router.getLocalAddress());

        Group group =  new Group(router, s.getGroupId(), account, true);
        demux.register(group);
        return group;
    }

    //public Group join(String name, String gid) {
    public Group join(Account account, String gid) {
        RequestInfo info = new RequestInfo(
                GroupJoin.Status.class, 1,
                TIMEOUT, true);

        List<GroupJoin.Status> statuses = router.deliverSync(new GroupJoin(account, gid), info, gid);
        if (statuses.isEmpty()) {
            throw new GroupOperationException("No response");
        }
        GroupJoin.Status s = statuses.get(0);
        if (s.failed()) {
            throw new GroupOperationException("Group join denied: " + s.getCode());
        }

        Group group =  new Group(router, s.getGroupId(), account, false);
        demux.register(group);
        return group;
    }

    public GroupDemux getDemux() {
        return demux;
    }
}

